#!/usr/bin/env python

from tz.util.day import str2day, day2str, day_today
from tz.db.pg import PG
from decimal import Decimal

def save_offer_ratio(com_id, day, offer, offer_price):
    price = last_close_price(com_id, day)
    if not price:
        return
    ratio = (1 + offer_price * offer / price) / (1 + offer)
    print(day, offer_price, offer, ratio)
    _save(com_id, day, ratio)

def save_dividend_ratio(com_id, day, dividend, split=1):
    price = last_close_price(com_id, day)
    if not price:
        return
    ratio = ((price - Decimal(dividend)) / Decimal(split)) / price
    _save(com_id, day, ratio)


TODAY = day_today()
def _save(com_id, day, ratio):
    if day>TODAY:
        return
    PG.insert(
        'stock.com_ratio',
        dict(
            com_id=com_id,
            day=day,
            ratio=ratio
        ),
        on_conflict="(com_id,day) DO UPDATE SET ratio=EXCLUDED.ratio"
    )




def last_close_price(com_id, day):
    price = PG.query_one(
        "SELECT close,day FROM stock.com_price WHERE com_id=%s AND day<%s ORDER BY day DESC LIMIT 1",
        (
            com_id, day
        )
    )
    if price:
        return price.close
    com = PG.select_one('stock.com', dict(id=com_id))
    price_beign = PG.select_one('stock.com_price', dict(
        com_id=com_id
    ), order="day", limit=1)
    if price_beign:
        begin_day = day2str(price_beign.day)
    else:
        begin_day = "无价格"
    print(
        com.id,
        com.code,
        com.name,
        "当前日", day2str(day),
        "价格起始日", begin_day,
    )


if __name__ == "__main__":
    print(
        last_close_price(4820, 16205)
    )
